package com.bishe.main.socketthread;

import com.bishe.util.HttpUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author 吃瓜
 * @date Created in 2021-05-28 9:36
 */
@Component
public class SocketThread {
    public static ServerSocket serverSocket = null;
    Logger logger = LoggerFactory.getLogger(getClass());

    public void runSocket() throws IOException {
        try {
            serverSocket = new ServerSocket(8081);
        } catch (IOException e) {
            logger.error("端口号占用: [{}]", "8081");
        }
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("thread-pool-%d").build();
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
                2, Integer.MAX_VALUE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), namedThreadFactory);
        while (true) {
            Socket socket = serverSocket.accept();
            threadPoolExecutor.execute(() -> {
                System.out.println("Socket client" + socket.getRemoteSocketAddress() + "成功连接");
                logger.error("Socket client" + socket.getRemoteSocketAddress() + "成功连接");
                m: while (true) {
                    String[] split = new String[4];
                    try {
                        // 如果socket连接断开，即客户端意外中断，那么 socket.getInputStream();代码将死循环报错
                        if (socket.isClosed()) {
                            System.out.println("客户端异常结束了");
                            break m;
                        }
                        System.out.println("服务器:33行");
                        InputStream is = socket.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        System.out.println("服务器:31");
                        // 如上述的死循环错误 下面这行也有可能发生。但只发生过一次无法检查错误。
                        // 也想不到更加可靠的办法。
//                        String command = br.readLine();
                        char[] msg = new char[128];
                        int read = br.read(msg);

//                        System.out.println("服务器:42 + command : " + command);
                        System.out.println("服务器:42 + read : " + read + ",msg : " + new String(msg) + "\n");
                        split = new String(msg).split("[+]");
                        String url = "http://localhost:8082/facilityData/addFacilityData?temperature="
                                + split[0] + "&humidity=" + split[1] + "&facilitynumber=" + split[2];
                        System.out.println(url);
                        HttpUtil.sendGet(url);

                    } catch (IOException e) {
                        break ;
                    } finally {
                        logger.error("temperature: {}, humidity: {}, 设备号: {}", split[0], split[1], split[2]);
                    }
                }
            });

        }
    }
}
